<template>
  <erp-form-popover
    :title="title"
    :field="field"
    :value="value"
    :props="props"
    :extra="extraCom"
    :options="options"
    :form="form"
    @value-change="handleValueChange"
    @update-id-field="handleUpdateField"
  />
</template>

<script>
import ErpFormPopover from './ErpFormPopover';
import {base as request} from '@/request';
/**
 * 客户选择组件
 * @author maolin
 */
export default {
  name: "ErpFormCustomer",
  components: {
    ErpFormPopover
  },
  props: {
    /**
     * 标题
     * @public
     */
    title: {
      type: String,
      default: '',
    },
    /**
     * 字段
     * @public
     */
    field: {
      type: String,
      default: ''
    },
    /**
     * 默认值
     * @public
     */
    value: {
      type: [Object, Number, Array, String],
      default () {
        return null;
      }
    },
    /**
     * 表单对象
     * @public
     */
    form: {
      type: Object,
      default () {
        return {
        };
      }
    },
    /**
     * [属性](./ErpFormPopover.html#Props)
     * @public
     */
    props: {
      type: Object,
      default () {
        return {
        };
      }
    },
    /**
     * 额外配置
     * ```js
     * return {
        // 表单需要的id字段
        idField: '',
        inputPlaceholder: '',
        modalTitle: '',
        modalWidth: null,
        modalHeight: null,
        // 模态框表格中name对应的字段名
        modalNameField: null,
        // 模态框表格中id对应的字段名
        modalIdField: null,
        // 是否转换为字符串
        needToString: false,
        // 获取额外远程字段，插入到表单
        extraRemoteConfig: {
          // 默认关闭
          enable: false,
          // api配置
          apiConfig: {
            // url: '/selOrderSell/lastselOrderSellDetail',
            // 参数
            // params: {},
            // 参数，以函数形式返回字符串, 会覆盖到params中，
            // paramsFunction: "return {form: form.bizUserId}",
            // 返回参数配置
            // resFunction: 'return res.data'
          }
        },
        // 关联额外字段，除了id和name之外还需要关联字段时
        extraData: [
          // {
          //     // 外部id
          //     field: "userId",
          //     // 内部id
          //     relatedField: "id",
          // }
        ]
      };
     * ```
     * @public
     */
    extra: {
      type: Object,
      default () {
        return {};
      }
    },
  },
  data() {
    const options = {
      "type": "singleSelect",
      "name": "basCustomerManager",
      "title": "客户列表",
      "table": {
        "props": {
          "resizable": true
        },
        "permissions": ["basCustomer:basCustomerList"],
        "rowKey": "id",
        "list": [
        ],
        "fields": [
          {"label": "客户编号", "width": "100", "fixed": null, "prop": "code", "sortable": "custom"},
          {"label": "客户名称", "width": "120", "fixed": null, "prop": "name"},
          {"label": "联系人", "width": "100", "fixed": null, "prop": "contact", "sortable": "custom"},
          {"label": "联系电话", "width": "120", "fixed": null, "prop": "mobile", "sortable": "custom"},
          {"label": "客户类型", "width": "100", "fixed": null, "prop": "types", "sortable": "custom", "template": "{{item.typesShowText}}"},
          {"label": "客户等级", "width": "100", "fixed": null, "prop": "grade", "sortable": "custom", "template": "{{item.gradeShowText}}"},
          {"label": "备注", "width": "", "fixed": null, "prop": "remark"},

        ],
        "border": false,
        "showPagination": true,
        "showOrderNumber": false,
        "selectable": false,
        "defaultExpandAll": true,
        "showExport": false,
        "customColumn": false,
        "operationWidth": "100"
      },
      "search": {
        "form": {
          "pageOrderBy": null,
          "pageOrderDir": null,
          "pageIndex": 1,
          "pageSize": 30
        },
        "showKeywordQuery": true,
        "headSearchPlaceholder": "客户名称",
        "showAdvancedQuery": false,
      },
      "apiList": {
        "list": "/basMaterial/basMaterialList",
        "dataSourceApi": {
          "url": "/basMaterial/basMaterialFieldListInit",
          "query" : {
            "isList":"0"
          }
        }
      },
      "components": {
      },
      "buttons": [
      ]
    };
    return {
      options: options,
      extraRemoteData: {}
    };
  },
  computed: {
    extraRemoteConfig () {
      return this.extraCom && this.extraCom.extraRemoteConfig ? this.extraCom.extraRemoteConfig : {};
    },
    enableExtraRemote () {
      return !!(this.extraRemoteConfig && this.extraRemoteConfig.enable);
    },
    extraRemoteApi () {
      return this.extraRemoteConfig && this.extraRemoteConfig.apiConfig ? this.extraRemoteConfig.apiConfig : {};
    },
    extraCom () {
      const defaultConfig = {
        // 表单需要的id字段
        idField: '',
        inputPlaceholder: '',
        modalTitle: '',
        modalWidth: null,
        modalHeight: null,
        // 模态框表格中name对应的字段名
        modalNameField: null,
        // 模态框表格中id对应的字段名
        modalIdField: null,
        // 是否转换为字符串
        needToString: false,
        // 获取额外远程字段，插入到表单
        extraRemoteConfig: {
          // 默认关闭
          enable: false,
          // api配置
          apiConfig: {
            // url: '/selOrderSell/lastselOrderSellDetail',
            // 参数
            // params: {},
            // 参数，以函数形式返回字符串, 会覆盖到params中，
            // paramsFunction: "return {form: form.bizUserId}",
            // 返回参数配置
            // resFunction: 'return res.data'
          }
        },
        // 关联额外字段，除了id和name之外还需要关联字段时
        extraData: [
          // {
          //     // 外部id
          //     field: "userId",
          //     // 内部id
          //     relatedField: "id",
          // }
        ]
      };
      return Object.assign(defaultConfig, this.extra);
    }
  },
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    /**
     * 表单值更新
     * @param {string|number} value 值
     * @public
     */
    handleValueChange (value) {
      this.$emit('value-change', value);
      if (this.enableExtraRemote) {
        this.getExtraRemoteData();
      }
    },
    /**
     * 更新表单其他值
     * @param {object} obj 表单其他值对象
     * @public
     */
    handleUpdateField (obj) {
      this.$emit('update-id-field', obj);
    },
    /**
     * 获取远程数据
     * @public
     */
    getExtraRemoteData () {
      if (this.extraRemoteApi && this.extraRemoteApi.url) {
        let params = this.extraRemoteApi.params || {};
        if (this.extraRemoteApi.paramsFunction) {
          let fParams = {};
          try {
            fParams = new Function('form', this.extraRemoteApi.paramsFunction)(this.form);
          }catch (e) {
            console.log('ErpFormCustomer配置paramsFunction失败');
            console.log(e);
          }
          params = Object.assign(params, fParams);
        }
        request.post(this.extraRemoteApi.url, params)
          .then(res => {
            let extraRemoteData = res.data;
            if (this.extraRemoteApi.resFunction) {
              try{
                extraRemoteData = new Function('res', this.extraRemoteApi.resFunction)(res);
              }catch (e) {
                console.log('ErpFormCustomer配置resFunction失败');
                console.log(e);
              }
            }
            this.updateForm(extraRemoteData);
          });
      }
    },
    /**
     * 更新表单字段
     * @param obj
     * @private
     */
    updateForm (obj) {
      const map = {
        "address": "address",
        "currencyId": "currencyId",
        "departId": "departId",
        "exchangeRate": "rate",
        "invoiceType": "invoiceType",
        "merchandiser": "merchandiser",
        "merchandiserShowText": "merchandiserShowText",
        "modeDelivery": "modeDelivery",
        "modeTransport": "modeTransport",
        "orderDate": "orderDate",
        "orderType": "orderType",
        "otherPrice": "otherPrice",
        "payMethod": "payMethod",
        "sellMethod": "sellMethod",
        "sellUserId": "sellUserId",
        "sellUserIdShowText": "sellUserIdShowText",
        "settleMethod": "settleMethod",
      };
      let updateFormData = {};
      for (let i in map) {
        updateFormData[map[i]] = obj[i];
      }
      this.$emit('update-id-field', updateFormData);
    }
  },
};
</script>

<style lang="scss" scoped>

</style>
